package com.ruiboyun.liveapp.ui;

import android.os.Handler;
import android.support.annotation.Nullable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.ruiboyun.liveapp.R;
import com.ruiboyun.liveapp.base.BaseActivity;
import com.ruiboyun.liveapp.base.Url;
import com.ruiboyun.liveapp.bean.LaunchBean;
import com.ruiboyun.liveapp.dialog.BaseDialog;
import com.ruiboyun.liveapp.presenter.impl.ConnectPresenterImpl;
import com.ruiboyun.liveapp.util.tool.EditorShare;
import com.ruiboyun.liveapp.view.ConnectView;


public class SplashActivity extends BaseActivity implements ConnectView {


    private ConnectPresenterImpl connectPresenter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_splash;
    }

    private long time;

    @Override
    protected void afterCreate(@Nullable Bundle savedInstanceState) {
        View decorView = getWindow().getDecorView();
        time = System.currentTimeMillis();

        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN;
        decorView.setSystemUiVisibility(uiOptions);
        connectPresenter = new ConnectPresenterImpl(this);
        connectPresenter.connect();
    }


    Handler handler = new Handler();

    @Override
    public void connectSuccess(LaunchBean launchBean) {
        Url.BASE_URL=launchBean.getUrl();
        if (System.currentTimeMillis()-time>2000){
            checkPort();
        }else {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    checkPort();
                }
            },2000);
        }
    }

    private void checkPort() {
        String string = EditorShare.getString(Url.PORT);
        if (TextUtils.isEmpty(string)){
            launcher(LoginActivity.class);
        }else {
            launcher(MainActivity.class);
        }
        finish();
    }

    @Override
    public void connectError(int errorCode) {
        BaseDialog baseDialog=new BaseDialog(this);
        baseDialog.setCancleText("退出").setConfirmText("重试")
                .setContent("无法连接服务器，是否尝试重试连接服务器？")
                .setOnConfirmListener(new BaseDialog.OnConfirmListener() {
                    @Override
                    public void onConfirm() {
                        connectPresenter.connect();
                    }

                    @Override
                    public void onCancle() {
                        finish();
                    }
                });
    }

    @Override
    public void showTips(String msg) {

    }


}
